package org.example.validate;

import com.google.common.cache.Cache;
import org.example.common.enums.AppGlobalKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;


@Component
public class PhoneTokenAuthenticationProvider implements AuthenticationProvider {

    private static final Logger logger = LoggerFactory.getLogger(PhoneTokenAuthenticationProvider.class);

    @Autowired
    @Qualifier("phoneUserServiceDetailService")
    private UserDetailsService userDetailsService;

    @Autowired
    @Qualifier("guavaCache")
    private Cache<String, Object> guavaCaCHe;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        PhoneAuthenticationToken usernamePasswordAuthenticationToken=
                (PhoneAuthenticationToken)authentication;

        Object phone = usernamePasswordAuthenticationToken.getPrincipal();//phone
        Object code = usernamePasswordAuthenticationToken.getCredentials();//code

        Object redisPhoneCode = guavaCaCHe.getIfPresent(AppGlobalKey.APP_USER_PHONE + String.valueOf(phone));
        logger.info("phone:{},code:{},redisPhoneCode:{}",phone,code,redisPhoneCode);
        if(!String.valueOf(code).equals(String.valueOf(redisPhoneCode))){
            throw new BadCredentialsException("验证码错误");
        }

        UserDetails userDetails = userDetailsService.loadUserByUsername(String.valueOf(phone));

//        UsernamePasswordAuthenticationToken result =
//                new UsernamePasswordAuthenticationToken(phone,null,userDetails.getAuthorities());
//        result.setDetails(userDetails);
        PhoneAuthenticationToken phoneAuthenticationToken = new PhoneAuthenticationToken(userDetails.getUsername(), null);
        phoneAuthenticationToken.setDetails(userDetails);

        guavaCaCHe.invalidate(AppGlobalKey.APP_USER_PHONE + String.valueOf(phone));//清除key

        return phoneAuthenticationToken;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return PhoneAuthenticationToken.class.isAssignableFrom(aClass);
    }
}
